package com.itboye.jinpuyiyuan.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.LoginOrRegisterActivity;
import com.itboye.jinpuyiyuan.activity.me.FeedBackActivity;
import com.itboye.jinpuyiyuan.activity.me.SetUpActivity;
import com.itboye.jinpuyiyuan.base.BaseFragment;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.logincontroller.LoginController;
import com.itboye.jinpuyiyuan.utils.logincontroller.LoginedState;
import com.itboye.jinpuyiyuan.utils.logincontroller.UnLoginState;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.CircleImageView;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.IsStringSPUtils;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2018/1/8 0008.
 */

public class MeDoctorFragment extends BaseFragment implements Observer {
    //title
    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft,topBar;


    private CheckBox drugRightBack;
    private TextView onlineTv,tvNikeNmae;
    private CircleImageView logoImg;
    private RelativeLayout updateOnline,me_feed_back,contactUsRL;

    private boolean isMeasured = false;
    private float distance;
    private BroadcastReceiver receiver,headReceiver;
    private boolean isDownload=false;
    private String uid,nick,sign;
    private int sex;
    private Bitmap logoBit;//个人信息图片的bit
    private PopupWindow callPop;
    private String logoUrl;


    private BranchAddressPresenter presenter;
    private int online_status;//在线状态
    @Override
    public int initView() {
        return R.layout.fragment_me_doctor;
    }

    @Override
    public void onMyActivityCreated() {
        leftImg.setVisibility(View.GONE);
        leftTv.setVisibility(View.GONE);
        tvTitle.setText("我的");
//        logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
//        tvNikeNmae.setText("请先登录");
       presenter=new BranchAddressPresenter(this);
       init();
       if (online_status==1){
           drugRightBack.setChecked(true);
       }else {
           drugRightBack.setChecked(false);
       }
       drugRightBack.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if (isChecked){

                   presenter.updateUserProfile(uid,nick,sign,sex,"","",1);
               }else {
                   presenter.updateUserProfile(uid,nick,sign,sex,"","",0);
               }
           }
       });
        initBroadcast();
    }

    @Override
    public void onClick(View v) {
    switch (v.getId()){
        case R.id.rlLeft:
        case R.id.leftTv:
            getActivity().finish();
            break;
        case R.id.updateOnline:
        case R.id.drugRightBack://在线
            if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                LoginController.setLoginState(new UnLoginState());
                startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
            }
            break;
        case R.id.rightImg://设置
            if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                LoginController.setLoginState(new UnLoginState());
                startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
            }else {
                Intent intent = new Intent(getActivity(), SetUpActivity.class);
                startActivity(intent);
            }
            break;

        //意见反馈
        case R.id.me_feed_back:
            if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                LoginController.setLoginState(new UnLoginState());
                startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
            }else {
                Intent intent = new Intent(getActivity(), FeedBackActivity.class);
                startActivity(intent);
            }
            break;
        //个人资料
        case R.id.logoImg:
            if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                LoginController.setLoginState(new UnLoginState());
            }else {
                LoginController.setLoginState(new LoginedState());
            }
            LoginController.PersonnalInfomaton(getActivity(),null);
            break;
        //联系我们
        case R.id.contactUsRL:
           showCallPhonePop();
            break;
    }
    }

//    private void initViewData() {
//        logoUrl= (String) SPUtils.get(getActivity().getApplication(),null,"personLogo","");
//        uid= (String) SPUtils.get(getActivity().getApplication(),null, Const.UID,"");
//        nick= (String) SPUtils.get(getActivity().getApplication(),null,Const.NICK,"");
//
//        //已登录
////            logoImg.setImageBitmap(XImageLoader.loadBitmap(Const.DoctorImg+uid));
//        if (logoUrl==null||logoUrl.equals("")){
//            Thread thread= new Thread() {
//                @Override
//                public void run() {
//                    logoBit=returnBitmap(Const.DoctorImg+uid);
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            logoImg.setImageBitmap(logoBit);
//                        }
//                    });
//                }
//            };
//            thread.start();
//            return;
//        }else {
//            Log.d("===xiugai==","hahahaha");
//            Bitmap bm = BitmapFactory.decodeFile(logoUrl);
//            logoImg.setImageBitmap(bm);
//        }
//        Log.d("nick==",nick);
//        tvNikeNmae.setText(nick);
//
//    }

    //设置头像
    public void init(){
        online_status= (int) SPUtils.get(getActivity().getApplication(),null,Const.ONLINE_STATUS,0);
        logoUrl= (String) SPUtils.get(getActivity().getApplication(),null,"personLogo","");
        uid= (String) SPUtils.get(getActivity().getApplication(),null,Const.UID,"");
        nick= (String) SPUtils.get(getActivity().getApplication(),null,Const.NICK,"");
        sign= (String) SPUtils.get(getActivity().getApplication(),null,Const.SIGN,"");
        sex= (int) SPUtils.get(getActivity().getApplication(),null,Const.SEX,3);
        Log.d("uid======gai",uid);
        Log.d("uid======gai",nick);
        if (uid==null||uid.equals("")){//未登录或已退出登录
            Log.d("==login in=","false"+"");
            logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
//                Glide.with(getActivity()).load(Const.DoctorImg+SPUtils.get(getActivity().getApplication(),null,Const.ID,1001)).into(logoImg);
            tvNikeNmae.setText("请先登录");
        }else { //已登录
//            logoImg.setImageBitmap(XImageLoader.loadBitmap(Const.DoctorImg+uid));
            if (logoUrl==null||logoUrl.equals("")){
                Thread thread= new Thread() {
                    @Override
                    public void run() {
                        logoBit=returnBitmap(Const.DoctorImg+uid);
                        if (logoBit==null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
                                }
                            });

                        }else {
                            Log.d("===logoUrl==",Const.DoctorImg+uid);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    logoImg.setImageBitmap(logoBit);
                                }
                            });
                        }

                    }
                };
                thread.start();
            }else {
                Bitmap bm = BitmapFactory.decodeFile(logoUrl);
                Log.d("===logoUrl==",logoUrl);
                logoImg.setImageBitmap(bm);
            }
            Log.d("nick==",nick);
            tvNikeNmae.setText(nick);
        }

    }
    //初始化广播
    public void initBroadcast(){
        //登录登出的广播
        receiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("=======",nick);
                init();
//                if (intent.getAction()==FilterUtil.EXITLOGIN){
//                    logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
////                Glide.with(getActivity()).load(Const.DoctorImg+SPUtils.get(getActivity().getApplication(),null,Const.ID,1001)).into(logoImg);
//                    tvNikeNmae.setText("请登录");
//                }else if (intent.getAction() ==FilterUtil.LOGIN){
//                    logoImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.login_logo));
////                Glide.with(getActivity()).load(Const.DoctorImg+SPUtils.get(getActivity().getApplication(),null,Const.ID,1001)).into(logoImg);
//                    tvNikeNmae.setText("请登录");
//                }

            }
        };
        //修改头像的广播
        headReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("===xiugai==","laile");
                init();
                Glide.with(getActivity()).load(Const.DoctorImg+uid).into(logoImg);
            }
        };
        getActivity().registerReceiver(headReceiver,new IntentFilter(FilterUtil.HEAD));
        getActivity().registerReceiver(receiver,new IntentFilter(FilterUtil.EXITLOGIN));
        getActivity().registerReceiver(receiver,new IntentFilter(FilterUtil.LOGIN));

    }
    /**
     * 根据图片的url路径获得Bitmap对象
     * @param url
     * @return
     */
    private Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }

    public void showCallPhonePop(){
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_callphone, null);
        callPop=new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);

        callPop.setAnimationStyle(R.style.popupwindow_anim_style);
        callPop.setFocusable(true);
        TextView cancelTv=inflate.findViewById(R.id.cancelTv);
        TextView callTv= inflate.findViewById(R.id.callTv);
        final TextView callNumberTv=inflate.findViewById(R.id.callNumberTv);
        inflate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callPop.dismiss();
            }
        });
        //取消
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callPop.dismiss();
            }
        });
        //呼叫
        callTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+"1008611"));
                startActivity(intent);
                callPop.dismiss();
            }
        });
        inflate.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        inflate.setFocusableInTouchMode(true); //comment by
        callPop.showAtLocation(inflate, Gravity.TOP,0,0);

    }

    @Override
    public void update(Observable o, Object arg) {

        ResultEntity resultEntity = handlerError(arg);
        if (resultEntity!=null){

            if (resultEntity.getEventType() ==BranchAddressPresenter.By_UserProfile_update_success){

                MAlert.alert("用户在线更新成功");
            }else if (resultEntity.getEventType() ==BranchAddressPresenter.By_UserProfile_update_fail){

                MAlert.alert("用户在线更新失败");
            }

        }
    }
}
